import mongodbHandle from '../handle/mongodbHandle'
import sessionHandle from '../handle/sessionHandle'
import rankHandle from '../handle/rankHandle'
import routes from './route'
var ObjectId = require('mongodb').ObjectId;
var utility = require("utility");
import app from '../app'
import * as moment from 'moment'
import crossServiceBattleHandle from '../handle/crossServiceBattleHandle'

const jwt = require('jsonwebtoken');

import utils from '../core/utils';
import redisHandle from 'src/handle/redisHandle';
// import arenaHandle from 'js/handle/arenaHandle';
import arenaAutoHandle from '../handle/arenaAutoHandle'
import arenaHandle from 'src/handle/arenaHandle';

routes.setLogin('selectOpponent', [], async (msg, session) => {
    let time = moment().add(-30, 'days').valueOf()
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let myScore = myData.arenaPoint || 0
    let addScore = 0
    if (myScore < 200 * arenaHandle.arenaScoreBaseTime) {
        addScore = 0
    } else if (myScore < 300 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.1)
    } else if (myScore < 400 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.12)
    } else if (myScore < 600 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.15)
    } else if (myScore < 800 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.2)
    } else {
        addScore = Math.floor(myScore * 0.25)
    }
    if (addScore < 10 * arenaHandle.arenaScoreBaseTime) {
        addScore = 10 * arenaHandle.arenaScoreBaseTime
    }

    let docs = await mongodbHandle.playerDao.findByPageAndSort({
        currentServerID: session.serverID,
        "loginTime": {
            $gt: time
        },
        "arenaPoint": {
            $lte: myScore + addScore
        },
    }, {
        "arenaPoint": -1
    }, 0, 50)
    let players: any[] = []
    if (docs && docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
            let doc = docs[i]
            if (doc._id.toString() !== session.pID.toString()) {
                players.push(doc)
            }
        }
    }
    if (players.length > 0) {
        let opponents = utils.getRandomArrayNoRepeat(4, players)
        opponents = opponents.map(item => {
            let team = []
            for (let i = 0; i < item.playerData.teamList.list.length; i++) {
                let partner = item.playerData.teamList.list[i]
                if (partner) {
                    team.push(partner.tID)
                }
            }
            return {
                id: item._id.toString(),
                name: item.playerData.baseInfo.name || '玩家' + item._id.toString().substr(-4),
                totalPower: item.totalPower || 0,
                team: team,
                point: item.arenaPoint
            }
        })
        return { err: 0, data: { opponents: opponents, myPoint: myScore } }
    } else {
        let docs = await mongodbHandle.playerDao.findByPageAndSort({
            currentServerID: session.serverID,
            "loginTime": {
                $gt: time
            },
            "arenaPoint": {
                $gte: myScore
            },
        }, {
            "arenaPoint": 1
        }, 0, 50)
        if (docs && docs.length > 1) {
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                if (doc._id.toString() !== session.pID.toString()) {
                    players.push(doc)
                }
            }
        }
        if (players.length > 0) {
            let opponents = utils.getRandomArrayNoRepeat(4, players)
            opponents = opponents.map(item => {
                let team = []
                for (let i = 0; i < item.playerData.teamList.list.length; i++) {
                    let partner = item.playerData.teamList.list[i]
                    if (partner) {
                        team.push(partner.tID)
                    }
                }
                return {
                    id: item._id.toString(),
                    name: item.playerData.playerName || '玩家' + item._id.toString().substr(-4),
                    totalPower: item.totalPower || 0,
                    team: team,
                    point: item.arenaPoint
                }
            })
            return { err: 0, data: { opponents: opponents, myPoint: myScore } }
        } else {
            let opponents = docs.map(item => {
                let team = []
                for (let i = 0; i < 5; i++) {
                    let partner = item.playerData.teamList.list[i]
                    if (partner) {
                        team.push(partner.tID)
                    }
                }
                return {
                    id: item._id.toString(),
                    name: item.playerData.playerName || '玩家' + item._id.toString().substr(0, 4),
                    totalPower: item.totalPower || 0,
                    team: team,
                    point: item.arenaPoint
                }
            })
            return { err: 0, data: { opponents: opponents, myPoint: myScore } }
        }
    }
})

routes.setLogin('getOpponent', [
    ['id', 'string']
], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.id) })
    delete doc.playerData.Bag
    delete doc.playerData.EquipmentBag
    delete doc.playerData.PetTeam
    delete doc.playerData.CardBag
    delete doc.playerData.BlackShop
    delete doc.playerData.Task
    return { err: 0, data: doc }
})

routes.setLogin('getBattleOpponent', [
    ['score', 'number'],
    ['power', 'number']
], async (msg, session) => {
    let opponent = null
    let time = moment().add(-30, 'days').valueOf()
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let myScore = myData.arenaPoint || 0
    let addScore = 0
    if (myScore < 200 * arenaHandle.arenaScoreBaseTime) {
        addScore = 0
    } else if (myScore < 300 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.1)
    } else if (myScore < 400 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.12)
    } else if (myScore < 600 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.15)
    } else if (myScore < 800 * arenaHandle.arenaScoreBaseTime) {
        addScore = Math.floor(myScore * 0.2)
    } else {
        addScore = Math.floor(myScore * 0.25)
    }
    if (addScore < 10 * arenaHandle.arenaScoreBaseTime) {
        addScore = 10 * arenaHandle.arenaScoreBaseTime
    }

    let docs = await mongodbHandle.playerDao.findByPageAndSort({
        currentServerID: session.serverID,
        "loginTime": {
            $gt: time
        },
        "arenaPoint": {
            $lte: myScore + addScore
        },
    }, {
        "arenaPoint": -1
    }, 0, 3)
    if (docs.length >= 1) {
        opponent = utils.getOneFromArray(docs)
        delete opponent.playerData.bag
        delete opponent.playerData.equipmentBag
        delete opponent.playerData.treasureBag
    }
    if (!opponent) {
        let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
        delete myData.playerData.bag
        delete myData.playerData.equipmentBag
        delete myData.playerData.treasureBag

        opponent = myData
    }
    
    return { err: 0, data: opponent }
})

routes.setLogin('getAreaList', [], async (msg, session, cb) => {
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let docs1 = await mongodbHandle.arenaDao.findByPageAndSort({
        pID1: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs2 = await mongodbHandle.arenaDao.findByPageAndSort({
        pID2: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs = docs1.concat(docs2)
    docs.sort((a1, a2) => {
        return a2.time - a1.time
    })
    docs = docs.slice(0, 20)
    docs.forEach(item => {
        item.team1 = []
        let playerData = JSON.parse(item.player1)
        item.power1 = playerData.baseInfo.maxPower || 0
        playerData.teamList.list.forEach((p) => {
            if (p) {
                item.team1.push(p.tID)
            }
        })
        item.team2 = []
        playerData = JSON.parse(item.player2)
        item.power2 = playerData.baseInfo.maxPower || 0
        playerData.teamList.list.forEach((p) => {
            if (p) {
                item.team2.push(p.tID)
            }
        })
        delete item.player1
        delete item.player2
    })

    let myRank = await mongodbHandle.playerDao.count({ _id: { $ne: session.pID }, arenaPoint: { $gt: myData.arenaPoint || 0 } }) + 1
    return { err: 0, data: { data: docs, arenaTimes: myData.arenaTimes, arenaPoint: myData.arenaPoint || 0, myRank } }
})


routes.setLogin('getAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.arenaDao.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getProAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.arenaDaoTest.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getProCsAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.csAarenaDaoTest.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getCsAreaList', [], async (msg, session, cb) => {
    let myInfoData = await redisHandle.zscore(app.config.gameName + 'csBattleScore', session.pID)
    let myInfo = crossServiceBattleHandle.getPlayerInfo(myInfoData)
    // let csArenaPoint = myData.csArenaPoint || 0
    let docs = await mongodbHandle.csAarenaDao.findByPageAndSort({
        pID1: session.pID
    }, {
        'time': -1
    }, 0, 25)
    docs.forEach(item => {
        delete item.player1
        delete item.player2
    })
    return { err: 0, data: { data: docs, csArenaInfo: myInfo } }
})

routes.setLogin('getCsAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.csAarenaDao.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})


routes.setLogin('saveArenaData', [
    ['p2ID', 'string'],
    ['player1', 'string'],
    ['player2', 'string'],
    ['addScore1', 'number'],
    ['addScore2', 'number'],
    ['result', 'boolean'],
    ['point', 'number'],
    ['version', 'string'],
    ['seed', 'number'],
    ['type', 'number', false]
], async (msg, session, cb) => {
    let { p2ID, player1, player2, addScore1, addScore2, result, version, seed, point, type } = msg
    let time = moment().startOf('day').valueOf()
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let otherData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(p2ID) })
    arenaAutoHandle.saveArenaData2(session.pID, p2ID, player1, player2, addScore1, addScore2, result, version, seed, point, myData, otherData)
    return { err: 0 }
})


routes.setNotLogin('getPowerRank', [
    ['serverID', 'number'],
    ['phone', 'string'],
    ['pid', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getPowerRank(serverID, phone)
    let myRank = await rankHandle.getPowerRankByPID(serverID, phone, pid)
    let rank = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank
        }
    }
})

routes.setNotLogin('getNightProgressRank', [
    ['serverID', 'number'],
    ['phone', 'string'],
    ['pid', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getNightProgressRank(serverID, phone)
    let myRank = await rankHandle.getNightProgressRankByPID(serverID, phone, pid)
    let rank = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank
        }
    }
})

routes.setNotLogin('getTownBoomingRank', [
    ['serverID', 'number'],
    ['phone', 'string'],
    ['pid', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getBoomingRank(serverID, phone)
    let myRank = await rankHandle.getBoomingRankByPID(serverID, phone, pid)
    let reward = await rankHandle.getBoomingRankReward(serverID, phone)
    let rank = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank,
            booming: reward
        }
    }
})

routes.setLogin('getEquipmentPowerRank', [
    ['serverID', 'number'],
    ['pid', 'string'],
    ['phone', 'string'],
    ['equipmentLabel', 'string'],
], async (msg) => {
    let { serverID, pid, phone, equipmentLabel } = msg
    let rankData = rankHandle.getEquipmentPowerRank(serverID, phone, equipmentLabel)
    let myRank = rankHandle.getEquipmentPowerRankByPID(serverID, pid, phone, equipmentLabel)
    let rank = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank
        }
    }
})

routes.setUserNotLogin('getArenaRank', [
    ['serverID', 'number'],
    ['pid', 'string']
], async (msg) => {
    let { serverID, pid } = msg
    let rankData = await rankHandle.getArenaRank(serverID)
    let myRank = await rankHandle.getArenaRankByPID(serverID, pid)
    let rank = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            myRank: myRank,
            rankData: rank
        }
    }
})




routes.setUserNotLogin('getMapProgressRank', [
    ['serverID', 'number'],
    ['pid', 'string'],
    ['phone', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getMapProgressRank(serverID, phone)
    let myRank = await rankHandle.getMapProgressRankByPID(serverID, phone, pid)
    let rank = [], rankMap = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank,
        }
    }
})


routes.setUserNotLogin('getDevilProgressRank', [
    ['serverID', 'number'],
    ['pid', 'string'],
    ['phone', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getDevilProgressRank(serverID, phone)
    let myRank = await rankHandle.getDevilProgressRankByPID(serverID, phone, pid)
    let rank = [],
        rankMap = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank,
        }
    }
})

routes.setUserNotLogin('getDeepProgressRank', [
    ['serverID', 'number'],
    ['pid', 'string'],
    ['phone', 'string']
], async (msg) => {
    let { serverID, phone, pid } = msg
    let rankData = await rankHandle.getDeepProgressRank(serverID, phone)
    let myRank = await rankHandle.getDeepProgressRankByPID(serverID, phone, pid)
    let rank = [],
        rankMap = []
    if (rankData) {
        rank = rankData.slice(0, 150)
    }
    return {
        err: 0, data: {
            rankData: rank,
            myRank,
        }
    }
})


